package com.example.demo.controller;

import com.example.demo.pojo.Product;
import com.example.demo.service.ProductService;
import com.example.demo.thread.Consumer;
import com.example.demo.thread.Depository;
import com.example.demo.thread.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService productService;

    @GetMapping("/load")
    public List read() {
        return productService.load();
    }

    @GetMapping("/store")
    public void write() {
        List<Product> products = productService.load();
        productService.store(products);
    }

    @PostMapping("/add")
    public void add(Product product) {
        productService.add(product);
    }

    @GetMapping("/getOne")
    public Product getOne(@RequestParam("id") Integer id) {
        return productService.getOne(id);
    }

    @GetMapping("deleteOne")
    public void deleteOne(@RequestParam("id") Integer id) {
        productService.deleteOne(id);
    }

    @PostMapping("update")
    public void update(Product product) {
        productService.update(product);
    }

    @GetMapping("produce")
    public void produce(@RequestParam("id") Integer id) {
        Product product = productService.getOne(id);
        if (product != null) {
            Depository depository = new Depository(product.getCapacity());
            Producer producer = new Producer(depository);
            producer.produce(id, 60);
            producer.produce(id, 50);
            producer.produce(id, 30);
            producer.produce(id, 40);
            Consumer consumer = new Consumer(depository);
            consumer.consume(id, 50);
            consumer.consume(id, 110);
        }
    }

    @GetMapping("consume")
    public void consume(@RequestParam("id") Integer id) {
        Product product = productService.getOne(id);
        if (product != null) {
            Depository depository = new Depository(product.getCapacity());
            Consumer consumer = new Consumer(depository);
            consumer.consume(id, 50);
            consumer.consume(id, 110);
        }
    }
}
